﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Crossroad.Core.Configs;
using Crossroad.Core.Exceptions;
using Crossroad.OAuth.Attributes;
using Crossroad.System.Api;
using Crossroad.System.User.Dto;
using Crossroad.System.User.Model;
using Crossroad.System.User.Service;
using Crossroad.System.User.Service.Impl;
using Crossroad.Utils.Extensions;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace Crossroad.System.User.Controller
{
    [ApiAuthorize]
    [Route("api/system/users")]
    public class IndexController : BaseApi
    {
        private readonly UserInfoService userInfoService;


        public IndexController(
            IUserInfoService userInfoServiceIpt
        )
        {
            userInfoService = userInfoServiceIpt as UserInfoService;
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="keywords"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        [HttpGet]
        public object GetList(
            int? pageIndex = null,
            int? pageSize = null,
            string keywords = "",
            string startDate = "",
            string endDate = ""
        )
        {
            //无分页列表查询
            if (pageIndex == null && pageSize == null)
                return userInfoService.GetList(queryable =>
                {
                    queryable.OrderBy((a) => a.createTime, OrderByType.Desc);

                    if (keywords.Contains())
                        queryable.Where(a => SqlFunc.Contains(a.nickName, keywords));
                    if (startDate.Contains() && endDate.Contains())
                        queryable.Where(a => SqlFunc.Between(
                            a.createTime
                            , startDate.FillStartTime().ToDateTime().ToTimeStamp()
                            , endDate.FillEndTime().ToDateTime().ToTimeStamp()
                        )
                    );
                });

            //有分页列表查询
            pageIndex = pageIndex ?? 1;
            pageSize = pageSize ?? AppConfig.DEFAULT_PAGE_SIZE;

            return userInfoService.GetPaging(
                pageIndex.Value,
                pageSize.Value,
                queryable =>
                {
                    queryable.OrderBy((a) => a.createTime, OrderByType.Desc);

                    if (keywords.Contains())
                        queryable.Where(a => SqlFunc.Contains(a.nickName, keywords));
                    if (startDate.Contains() && endDate.Contains())
                        queryable.Where(a => SqlFunc.Between(
                            a.createTime
                            , startDate.FillStartTime().ToDateTime().ToTimeStamp()
                            , endDate.FillEndTime().ToDateTime().ToTimeStamp()
                        )
                    );
                }
            );
        }

        /// <summary>
        /// 查询当前登录的用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("info")]
        public object GetInfo()
        {
            return CurrentUser;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [ApiAuthorize(false)]
        [HttpPost("login")]
        public object Login(
            [FromBody] JObject parameter
        )
        {
            var param = new
            {
                clientId = parameter.Get<string>("clientId") ?? parameter.Get<string>("client_id"),
                clientSecret = parameter.Get<string>("clientSecret") ?? parameter.Get<string>("client_secret"),
                appId = parameter.Get<string>("appId") ?? parameter.Get<string>("app_id"),
                loginMode = parameter.Get<string>("loginMode") ?? parameter.Get<string>("login_mode"),
                username = parameter.Get<string>("username"),
                password = parameter.Get<string>("password"),
            };

            return userInfoService.Login(
                param.clientId,
                param.clientSecret,
                param.appId,
                param.loginMode,
                param.username,
                param.password
            );
        }

        /// <summary>
        /// 查询登录用户详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("login/info")]
        public object GetLoginUserInfo()
        {
            var user = CurrentUser;
            return new
            {
                userInfo = new
                {
                    user.username,
                    name = user.nickName,
                    user.avatar,
                },
                roles = "admin",
                permission = new []
                {
                    "sys_crud_btn_add",
                    "sys_crud_btn_export",
                    "sys_menu_btn_add",
                    "sys_menu_btn_edit",
                    "sys_menu_btn_del",
                    "sys_role_btn1",
                    "sys_role_btn2",
                    "sys_role_btn3",
                    "sys_role_btn4",
                    "sys_role_btn5",
                    "sys_role_btn6"
                }
            };
        }

        /// <summary>
        /// 新增一个用户
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [HttpPost]
        public object CreateAt(
            [FromBody] UserInfo parameter
        )
        {
            parameter.creatorId = CurrentUser.id;
            return userInfoService.CreateAt(parameter);
        }

        /// <summary>
        /// 修改指定用户
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="key">用户的key</param>
        /// <returns></returns>
        [HttpPatch("{key}")]
        public object UpdateAt(
            [FromBody] UserInfoDto parameter,
            string key = ""
        )
        {
            parameter.uniqueKey = key;

            return userInfoService.UpdateAt(parameter);
        }

        /// <summary>
        /// 修改自己的信息
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [HttpPatch("mine/info")]
        public object UpdateMineInfo(
            [FromBody] UserInfoDto parameter
        )
        {
            UserInfo model = new UserInfo(false)
            {
                id = CurrentUser.id,
                nickName = parameter.nickName,
                avatar = parameter.avatar,
                phone = parameter.phone,
                email = parameter.email,
            };

            return userInfoService.UpdateAt(model);
        }

        /// <summary>
        /// 修改自己密码
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [HttpPatch("mine/pwd")]
        public object UpdateMinePwd(
            [FromBody] JObject parameter
        )
        {
            var param = new
            {
                oldPwd = parameter.Get<string>("oldpassword"),
                newPwd = parameter.Get<string>("newpassword"),
                newPwdConfirm = parameter.Get<string>("newpasswords"),
            };

            if (!CurrentUser.password.Equals(param.oldPwd))
                throw new LogicException("原密码错误！");
            if(!param.newPwd.Equals(param.newPwdConfirm))
                throw new LogicException("两次输入的新密码不一样！");

            UserInfo model = new UserInfo(false)
            {
                id = CurrentUser.id,
                password = param.newPwd
            };
            userInfoService.UpdateAt(model);

            return true;
        }


        /// <summary>
        /// 删除一个用户
        /// </summary>
        /// <param name="key"></param>
        [HttpDelete]
        [Route("{key}")]
        public object DeleteAt(string key)
        {
            userInfoService.DeleteAt(new UserInfoDto
            {
                uniqueKey = key,
            });

            return true;
        }


    }
}